package cn.jingyinghui.controller;

import cn.jingyinghui.service.DoubaoNormalService;
import cn.jingyinghui.service.DoubaoTuiliService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import java.time.Duration;
import io.reactivex.Flowable;
import java.util.concurrent.TimeUnit;


/**
 * 这段代码太失败了。
 * 服务器总是会无故断开连接，暂时还不知道为什么
 */
@RestController
public class DoubaoController {

    @Autowired
    private DoubaoTuiliService doubaoTuiliService;

    @Autowired
    private DoubaoNormalService doubaoNormalService;

//    @GetMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
//    public Publisher<String> chat(@RequestParam String message) {
//        return Flux.from(doubaoService.getStreamResponse(message));
//    }





    @GetMapping(value = "/chatTl", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> chatTl(@RequestParam String message) {
        return doubaoNormalService.getStreamResponse(message)
            .timeout(Duration.ofMinutes(5))
            .retry(3)
            .map(content -> "data: " + content + "\n\n")
            .concatWith(Flux.just("data: [DONE]\n\n"))
            .onErrorResume(e -> {
                String errorMsg = e.getMessage() != null ? e.getMessage() : "Unknown error";
                return Flux.just("data: {\"error\": \"" + errorMsg + "\"}\n\n", "data: [DONE]\n\n");
            })
            .doOnError(e -> {
                System.err.println("Error in stream: " + e.getMessage());
                e.printStackTrace();
            })
            .doFinally(signalType -> {
                System.out.println("Stream completed with signal: " + signalType);
            });
    }


    @PostMapping(value = "/chatNormal", produces = "text/text-stream;charset=UTF-8")
    public Flux<String> chatNormal(@RequestParam String message) {
        return Flux.create(sink -> {
            doubaoNormalService.getStreamResponse(message).subscribe(
                    content -> {
                        // 格式化 SSE 消息
                    /*String sseMessage = "data: " + content + "\n\n";
                    System.out.println("sseMessage = " + sseMessage);
                    sink.next(sseMessage);*/


//                    System.out.print(content);
                        sink.next(content);


                        /*sink.next(content);*/
                    },
                    throwable -> {
                        // 处理错误
                        sink.error(throwable);
                    },
                    () -> {
                        // 完成流
                        // 完成流，发送结束标志
                    /*String endMessage = "data: [DONE]\n\n";
                    sink.next(endMessage);*/
                        sink.complete();
                    }
            );
        });
    }





}
